package thread;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

class MyCache
{
    private volatile Map<String,Object> map = new HashMap<>();
    private ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();

    public void put(String key,Object value)
    {
        rwLock.writeLock().lock();
        try{
            System.out.println(Thread.currentThread().getName()+"\t 正在写入："+key);
            try{
                TimeUnit.MILLISECONDS.sleep(300);
            }catch (Exception e){
                e.printStackTrace();
            }
            map.put(key,value);
            System.out.println(Thread.currentThread().getName()+"\t 写入完成：");
        }finally {
            rwLock.writeLock().unlock();
        }
    }

    public void get(String key)
    {
        rwLock.readLock().lock();
        try{
            System.out.println(Thread.currentThread().getName()+"\t 正在读取："+key);
            try{
                TimeUnit.MILLISECONDS.sleep(300);
            }catch (Exception e){
                e.printStackTrace();
            }
            Object object = map.get(key);
            System.out.println(Thread.currentThread().getName()+"\t 读取完成：");
        }finally {
            rwLock.readLock().unlock();
        }
    }
}
/**
 * 独占锁：锁一次只能被一个线程持有
 * 共享锁：锁可以被多个线程持有
 * ReentrantReadWriteLock其读锁是共享锁，其写锁是独占锁
 * 读锁的共享锁可保证并发读是非常高效的，读写，写读，写写的过程是互斥的
 */
public class ReadWriteLockDemo {
    public static void main(String[] args) {
        MyCache myCache = new MyCache();

        for(int i = 1;i <= 5;i++){
            final int tempInt = i;
            new Thread(() -> {
                try{
                    myCache.put(tempInt+"",tempInt+"");
                }catch (Exception e){
                    e.printStackTrace();
                }
            },String.valueOf(tempInt)).start();
        }

        for(int i = 1;i <= 5;i++){
            final int tempInt = i;
            new Thread(() -> {
                try{
                    myCache.get(tempInt+"");
                }catch (Exception e){
                    e.printStackTrace();
                }
            },String.valueOf(tempInt)).start();
        }
    }
}
